/**
 * 设备状态, 流批数据汇总
 */

function Logger() {}
Logger.prototype.info = function (str) {
	print(str);
};
var logger = new Logger();
// 批流测试数据

function DeviceStatusBatchData() {}
// forEach函数
function forEach(arr, fn) {
	Array.prototype.forEach.call(arr, fn);
}
function filter(arr, cmpfn) {
	Array.prototype.filter.call(arr, cmpfn);
}
// 分组函数
function GroupBy(array, groupIdFn, handle) {
	var groups = {};
	logger.info("<<<<<<<<<<<<>>>>>>" + (array['forEach']));
	// 这里不支持直接调用forEach方法
	forEach(array, function (item) {
		logger.info("++++++++++++++");
		var groupId = JSON.stringify(groupIdFn(item));
		handle(groups, groupId, item);
	});
	return groups;
}

// 根据批的数据, 创建流的默认数据, 如果查询的流的数据为空, 流就用该默认数据
var defaultStreamData = {};
if (batchData["data"]) {
	logger.info("=================");
	defaultStreamData = GroupBy(batchData.data, function(item) {
		logger.info("************** item : " + JSON.stringify(item));
		return [item.thingname, item.status];
	}, function (groups, groupId, item) {
		logger.info("<<<<<<<< groups: " + groups + ", groupId: " + groupId + ", item: " + JSON.stringify(item));
		if (!!!groups[groupId]) {
			groups[groupId] = 0;
		}
	});
}
logger.info("=================");
//这里如果想要按照name进行分组即如下：
var streamGrouped = GroupBy(streamData.data, function (item) {
	return [item.thingName, item.status];
}, function (groups, groupId, item) {
	// 这里利用对象的key值唯一性的，创建数组
	if (!!!groups[groupId]) {
		groups[groupId] = 0;
	}
	groups[groupId] += item.cnt;
});

Object.keys(streamGrouped).forEach(function (group) {
	defaultStreamData[group] = streamGrouped[group];
});

logger.info("default stream datas: " + JSON.stringify(defaultStreamData));
logger.info("stream grouped: " + JSON.stringify(streamGrouped));

// 将stream合并到batch中
function createBatchDataRow(thingname, status, hour, cnt) {
	var obj = new DeviceStatusBatchData();
	obj.thingname = thingname;
	obj.status = status;
	obj.hour = hour;
	obj.cnt = cnt;
	return obj;
}
Object.keys(defaultStreamData).forEach(function (group) {
	var groupArr = JSON.parse(group);
	var thingname = groupArr[0];
	var status = groupArr[1];
	var hour = new Date().getHours();
	var cnt = defaultStreamData[group];
	
	batchData.data.push(createBatchDataRow(thingname, status, hour, cnt));
});

logger.info("stream and batch data: " + JSON.stringify(batchData));







